package com.pandarouter;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import javax.naming.spi.DirStateFactory.Result;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class Req implements Runnable{
	private String reqID = "";
	private String reqUrl = "";
	private String resultBody = "";
	private String resultType = "";
	private String lastModified = "";
	private String mapUrl = "";
	public void run(){
		Worker.threadsNum++;
		List<NameValuePair> appReq = new ArrayList<NameValuePair>();
		List<NameValuePair> appRes = new ArrayList<NameValuePair>();
		try{
			System.out.println("Thread inited " + System.currentTimeMillis());
			appReq.add(new BasicNameValuePair("pandarouter_data","1"));
			appReq.add(new BasicNameValuePair("pandarouter_type","2"));
			String rString = HttpPost(Worker.remoteUrl, appReq);
			if(!rString.equals("0") && parse(rString)){
				mapping();
				appRes.add(new BasicNameValuePair("pandarouter_data","type:"+resultType+"\r\nlastModified:"+lastModified+"\r\nbody:"+resultBody));
				appRes.add(new BasicNameValuePair("pandarouter_type","3"));
				appRes.add(new BasicNameValuePair("pandarouter_reqid",reqID));
				appRes.add(new BasicNameValuePair("pandarouter_localurl",Worker.localUrl));
				Worker.echo(HttpPost(Worker.remoteUrl, appRes));
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			Worker.threadsNum--;
		}
	}
	private Boolean parse(String body){
		Worker.isActive = true;
		Worker.lastActived = System.currentTimeMillis();
		String[] paramArr = body.split("\r\n");
		int i;
		for(i=0;i<paramArr.length;i++){
			if(paramArr[i].indexOf("id:") == 0)
				reqID = paramArr[i].substring(3);
			if(paramArr[i].indexOf("url:") == 0)
				reqUrl = paramArr[i].substring(4);
		}
		if(!reqID.isEmpty())
			return true;
		else
			return false;
	};
	private void mapping(){
		mapUrl = Worker.localUrl + reqUrl.replace(Worker.localUrl, "");
		HttpGet(mapUrl);
	}
	// 向API提交数据
    public void HttpGet(String url){
    	String jsonStr = "";
    	BufferedReader in = null;
        try{
        	URL realUrl = new URL(url);
        	URLConnection connection = realUrl.openConnection();
        	connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","");
            connection.setRequestProperty("Cookie", "");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("referer", url);
            connection.connect();
            resultType = connection.getHeaderField("content-type");
            //System.out.println(connection.);
            lastModified = connection.getHeaderField("Last-Modified");
            InputStream iStream = connection.getInputStream();
            byte[] getData = readInputStream(iStream);   
            resultBody = encode(getData);
        }catch(Exception e){
        	e.printStackTrace();
        }finally{
        	try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
            }
        }
    }
    public static  byte[] readInputStream(InputStream inputStream) {
        byte[] buffer = new byte[1024];    
        int len = 0;    
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
        try {
            while((len = inputStream.read(buffer)) != -1) {    
                bos.write(buffer, 0, len);    
            }    
            bos.close();    
		} catch (Exception e) {
		}
        return bos.toByteArray();    
    }
	// 向API提交数据
    public static String HttpPost(String url,List<NameValuePair> params){
    	String jsonStr = "";
        try{
        	CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        	HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(params));
            CloseableHttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            jsonStr = EntityUtils.toString(entity, "utf-8");
            httppost.releaseConnection();
        }catch(Exception e){
        	e.printStackTrace();
        }
        return jsonStr;
    }
    public String encode(final byte[] bytes) {  
        return new String(Base64.encodeBase64(bytes));  
    }  
}
